var dbConfig = require('../util/dbconfig');
const respont = require('../util/dao');


function rand(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

ValidatePhoneCode = [];
let sendCodeP = (phone) => {
    for (var item of ValidatePhoneCode) {
        if (phone == item.phone) {
            return true
        }
    }
    return false
}

// 写：验证码是否匹配的方法
let findCodeAndPhone = (phone, code) => {
    for (var item of ValidatePhoneCode) {
        // 如果相等
        if (phone == item.phone && code == item.code) {
            return 'login'
        }
    }
    return 'error'
}
// 模拟验证码发送接口
sendCode = (req, res) => {
    let phone = req.query.phone;
    if (sendCodeP(phone)) {
        res.send({
            'code': 400,
            'msg': '已发送过验证码，请稍后再发'
        })
    }
    let code = rand(1000, 9999);
    ValidatePhoneCode.push({
        'phone': phone,
        'code': code
    })
    console.log(ValidatePhoneCode)
    res.send({
        'code': 200,
        'msg': '发送成功'
    });
    console.log(code)
}
// 验证码登录接口
codePhoneLogin = (req, res) => {
    let {phone, code} = req.query
    // 该手机是否发送过验证码
    if (sendCodeP(phone)) {
        // 验证码是否匹配
        let status = findCodeAndPhone(phone, code);
        // 判断一下
        if (status == 'login') {
            //验证成功
            res.send({
                'code': 200,
                'msg': '验证成功'
            })
        } else if (status == 'error') {
            res.send({
                'code': 200,
                'msg': '验证失败'
            })
        }
    } else {
        res.send({
            'code': 400,
            'msg': '未发送验证码'
        })
    }
}
login = (req, res, next) => {
    let body = req.body
    let sql = 'select * from user where user_name = ?'
    let sqlArr = [body.userName]
    var callBack = (err, data) => {
        if (err) {
            return next(respont.fail(500, '失败'))
        }
        if (data[0] == null) {
            res.send(respont.fail(200, '用户名不存在'))
            return
        }
        if (data[0].password === body.password) {
            data[0].password = undefined
            let payload = {id: data[0].id, username: data[0].username}
            data[0].token = respont.createToken(payload)
            res.send(respont.ok(data[0]))
            return
        }
        res.send(respont.fail(200, '密码错误'))
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack)
}

register = (req, res, next) => {
    let body = req.body
    body.createTime = new Date()
    let s = 'select * from user where user_name = ?'
    let arr = [body.userName]
    var selectBack = (err,data)=>{
        if (err) {
            return next(respont.fail(500, '操作失败'))
        }
        if (data.length > 0){
            res.send(respont.fail(500,'该用户已存在'))
            return
        }
        let sql = 'INSERT INTO user(`nick_name`, `password`, `user_name`, `sex`, `phone`, `id_number`, `create_time`, `address`) VALUES (?,?,?,?,?,?,?,?)'
        let sqlArr = [body.nickName,body.password,body.userName,body.sex,body.phone,body.idNumber,body.createTime,body.address]
        var callBack = (err,data)=>{
            if (err) {
                console.log(err)
                return next(respont.fail(500, '失败'))
            }
            if (data.length === 0){
                res.send(respont.fail(500,'注册失败'))
                return
            }
            res.send(respont.ok())
        }
        dbConfig.sqlConnect(sql,sqlArr,callBack)
    }
   dbConfig.sqlConnect(s,arr,selectBack)
}
amend = (req,res,next)=>{
    let body = req.body
    let sql = 'update user set nick_name = ?,sex = ?,phone = ?,id_number = ?,address = ? where id=?'
    let sqlArr = [body.nickName,body.sex,body.phone,body.idNumber,body.address,body.id]
    var callBack = (err,data)=>{
        if (err) {
            console.log(err)
            return next(respont.fail(500, '操作失败'))
        }
        res.send(respont.ok())
    }
    dbConfig.sqlConnect(sql,sqlArr,callBack)
}
module.exports = {
    sendCode,
    codePhoneLogin,
    login,
    register,
    amend
}